<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class Coupons extends Model
{
    use SoftDelete;
    protected $deleteTime = 'deletetime';
    protected $hidden = ['online', 'deletetime', 'createtime', 'updatetime', 'weigh'];

    public function getImageAttr($value)
    {
        return $value ? request()->domain().$value : '';
    }

    public static function getCoupons()
    {
        return self::where('online', 'yes')->whereTime('start_time', '<', time())->whereTime('end_time', '>', time())->select();
    }

    /**
     * 优惠券列表
     */
    public static function getByCategoryId($category_id, $length = 20)
    {
        $where = [
            'online' => ['=', '1']
        ];
        if ($category_id) {
            $where['category_id'] = ['=', $category_id];
        }
        $coupons = self::with('vip')->where($where)->order('weigh desc')->paginate($length);
        return $coupons->items();
    }

    public function vip()
    {
        return $this->belongsToMany(UserVip::class, 'coupon_vip', 'user_vip_id', 'coupon_id');
    }

}
